import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/api/special_list.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/job_ticket/common/common_work_all/common_work_all_controller.dart';
import 'package:get/get.dart';

class CommonJobClosedController extends GetxController {
  //作业总页面controller
  final workAllPageController = Get.find<CommonWorkAllController>();

  //作业票id
  late String ticketReceiptId;

  //  气体检测计时
  int gasMilliseconds = 0;

  // 作业倒计时
  int jobMilliseconds = 0;

  //关闭节点数据
  ExecuteWorkCheckList workCheck = ExecuteWorkCheckList();

  @override
  void onInit() {
    super.onInit();
    // 初始化页面列表
    initData();
    // 获取数据气体检测有效期
    if (workAllPageController.receiptType == 1 || workAllPageController.receiptType == 2) {
      getTicketReceiptValidDate();
    }
    // 加载作业申请数据,主要为拿到作业时间
    initApplicationDate();
  }

  ///初始化数据
  initData() async {
    //作业票id
    ticketReceiptId = workAllPageController.executeEntity.ticketReceiptId!;
    workCheck = ExecuteWorkCheckList();
    //获取数据-安全措施数据
    final res = await HttpUtil().generateGetRequest<List<ExecuteWorkCheckList>>(Interface.getListCheckById,
        queryParameters: {'ticketReceiptId': workAllPageController.executeEntity.ticketReceiptId}).execute();
    res.onSuccess((result) {
      for (var item in result.data!) {
        if (item.checkProject == '完工验收') {
          workAllPageController.executeEntity.workCheckList = item;
          break;
        }
      }
    });
    //如果为空,初始化数据
    if (workAllPageController.executeEntity.workCheckList!.checkProject!.isEmpty) {
      workAllPageController.executeEntity.workCheckList!
        ..ticketReceiptId = workAllPageController.executeEntity.ticketReceiptId!
        ..checkProject = '完工验收'
        ..sort = 99;
    }
    update();
  }

  /// 加载作业申请数据,主要为拿到作业时间
  Future<void> initApplicationDate() async {
    //获取数据-作业申请数据
    final res =
        await HttpUtil().generateGetRequest<ExecuteEntity>(Interface.getTicketReceiptDetail, queryParameters: {'ticketReceiptId': ticketReceiptId}).execute();
    res.onSuccess((result) {
      workAllPageController.executeEntity.endDate = result.data!.endDate;
    });
    update();
  }

  ///获取数据气体检测有效期
  getTicketReceiptValidDate() async {
    final res = await SpecialListApis.getListConfigByTicketReceiptId(ticketReceiptId).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.gasDetectionValidDate != 0) {
        gasMilliseconds = result.data!.gasDetectionValidDate!;
        jobMilliseconds = result.data!.ticketReceiptValidDate!;
        update();
      }
    });
  }
}
